/*
 * Copyright (c) 2012 OptiCare Systems Ltd
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 *
 * Authors: Kevin Martin (kev82@khn.org.uk)
 */
#ifndef __LUA_OPTICARE_EXTENSIONS_HEADER__
#define __LUA_OPTICARE_EXTENSIONS_HEADER__

#include <string>
#include <lua5.2/lua.hpp>
#include <boost/shared_ptr.hpp>
#include <ostream>
#include <boost/function.hpp>
#include <boost/property_tree/ptree.hpp>
#include <vector>

void luaOE_throwerror(lua_State *l, std::string err = "");

void luaOE_require(lua_State *l, const std::string &package);

class luaOE_serialized_obj
{
public:
	virtual ~luaOE_serialized_obj() {}

	//These should be protected, but they can't be because c++ is a bit silly
	//See http://www.cplusplus.com/forum/general/7997/
	virtual void int_unserializeAsState(lua_State *s) const =0;
	virtual void int_unserializeAsJSON(std::ostream &os,
	 boost::function<std::string (std::string)> quoter) const =0;
	virtual void int_unserializeAsLuaString(std::ostream &os,
	 boost::function<std::string (std::string)> quoter) const =0;
	virtual void int_unserializeAsPTree(boost::property_tree::ptree &pt, 
	 std::vector<std::string> &path) const =0; 

	void unserializeState(lua_State *s);
	std::string unserializeJSON();
	std::string unserializeLuaString();
	boost::property_tree::ptree unserializePTree();
};

boost::shared_ptr<luaOE_serialized_obj> luaOE_serialize(lua_State *s, int stackidx);
//This runs the code and puts all the return values in an array with indices rv1, rv2, .. rvn
boost::shared_ptr<luaOE_serialized_obj> luaOE_serialize_string(const std::string &s);

template<typename T>int luaOE_protected_call(T func, lua_State *l) {
    try {
        return func(l);
    } catch(std::exception &e) {
        luaL_error(l, e.what());
    } catch (...) {
        luaL_error(l, "Undetermind exception");
    }
    assert("unreachable code"==0x0);
}

#endif
